package com.sdy.resdir.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.auth.api.model.UserInfo;
import com.sdy.auth.client.service.SsoService;
import com.sdy.common.model.BizException;
import com.sdy.common.model.PageQuery;
import com.sdy.common.model.PageResult;
import com.sdy.common.utils.Assert;
import com.sdy.mvc.utils.JsonUtil;
import com.sdy.resdir.biz.model.RdParameterInformation;
import com.sdy.resdir.biz.model.RdResDetailsApi;
import com.sdy.resdir.biz.model.RdResourceDir;
import com.sdy.resdir.biz.service.RdParameterInformationService;
import com.sdy.resdir.biz.service.RdResDetailsApiService;
import com.sdy.resdir.biz.service.RdResManagementService;
import com.sdy.resdir.biz.model.RdResManagement;
import com.sdy.common.model.Response;
import com.sdy.resdir.biz.service.RdResourceDirService;
import com.sdy.resdir.biz.util.PageUtil;
import com.sdy.resdir.biz.vo.UserInfoVo;
import com.sdy.resdir.biz.vo.UserResListVo;
import com.sdy.usercenter.api.UserQueryApi;
import com.sdy.usercenter.api.dto.DeptDto;
import com.sdy.usercenter.api.dto.UserDTO;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sdy.mvc.controller.BaseController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 资源管理,关联用户所拥有资源 前端控制器
 * </p>
 *
 * @author hyh
 * @since 2019-10-29
 */
@Slf4j
@RestController
@SuppressWarnings("unchecked")
@RequestMapping("/rdResManagement")
@Api(tags = "用户资源管理Api")
public class RdResManagementController extends BaseController {
    @Autowired
    private RdResManagementService rdResManagementService;
    @Autowired
    private UserQueryApi userQueryApi;
    @Autowired
    private SsoService ssoService;
    @Autowired
    private RdParameterInformationService rdParameterInformationService;
    @Autowired
    private RdResDetailsApiService rdResDetailsApiService;
    @Autowired
    private RdResourceDirService rdResourceDirService;

    @ApiOperation(value = "获取用户该某个自建系统下某个ip中绑定的和未绑定的资源列表", response = UserResListVo.class)
    @ApiImplicitParam(name = "ipId", value = "IP的id")
    @GetMapping("/getUserIpBingResList")
    public Response getUserIpBindResList(Page page, Integer ipId, HttpServletRequest request) throws BizException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "当前用户未登录");
        List<UserResListVo> userBindResList = rdResManagementService.getUserBindResList(userInfo.getUserId(), ipId, page);
        PageUtil pageData = new PageUtil(page.getSize(), page.getCurrent(), userBindResList);
        return Response.success(pageData);
    }


    @ApiOperation(value = "将用户的某个页面类资源或者服务类资源对某个人进行授权")
    @PostMapping("/isApprovalRes")
    public Response isApprovalRes(@RequestBody @ApiParam(name = "userId,resId") Map<String, Object> map) throws BizException {
        Integer userId = (Integer) map.get("userId");
        Integer resId = (Integer) map.get("resId");
        Assert.isTrue(null == userId || null == resId, "用户id或者资源id不可为空");
        int approvalRes = rdResManagementService.isApprovalRes(userId, resId);
        return approvalRes == 1 ? Response.success() : Response.error();
    }


    @ApiOperation(value = "一键授权,对列表的所有部门人员进行该资源的授权")
    @PostMapping("/oneKeyIsApprovalRes")
    public Response oneKeyIsApprovalRes(@RequestBody @ApiParam(name = "deptId,resId,userName,type") Map<String, Object> map) throws BizException {
        Integer deptId = (Integer) map.get("deptId");
        Integer resId = (Integer) map.get("resId");
        String userName = (String) map.get("userName");
        Integer type = (Integer) map.get("type");
        Assert.isTrue(null == deptId || null == resId || null == type, "部门id或者资源id不可为空");
        int approvalState = rdResManagementService.oneKeyIsApprovalRes(deptId, resId, userName, type);
        return approvalState == 1 ? Response.success() : Response.error();
    }

    @ApiOperation(value = "根据当前用户获取该用户所管理的部门以及子部门")
    @ApiImplicitParam(name = "parenId", value = "部门父ID")
    @GetMapping("/getDeptList")
    public Response getDeptListByUserId(HttpServletRequest request, Integer parentId) throws BizException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "未登录");
        List<DeptDto> deptDtos = userQueryApi.listUserManageDept(userInfo.getUserId(), parentId);
        return Response.success(deptDtos);
    }

    @ApiOperation(value = "点击授权管理后查询当前用户所在部门的用户列表", response = UserInfoVo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptId", value = "部门ID"),
            @ApiImplicitParam(name = "resId", value = "资源ID"),
            @ApiImplicitParam(name = "userName", value = "用户名称")
    })
    @GetMapping("/getDeptPerList")
    public Response getDeptPerList(Page page, Integer deptId, Integer resId, String userName) throws Exception {
        userName = URLDecoder.decode(userName, "UTF-8");
        PageQuery pageQuery = new PageQuery(page.getCurrent(), page.getSize());
        pageQuery.setCurrent(page.getCurrent());
        pageQuery.setSize(page.getSize());
        PageResult<UserDTO> pageResult = userQueryApi.pageUserInDept(pageQuery, deptId, userName, false);
        PageResult<UserInfoVo> userPage = JsonUtil.convertPage2(pageResult, UserInfoVo.class);
        // 给所有用户设置是否拥有资源
        userPage.getRecords().forEach(user -> user.setIsHave(0));
        // 根据查询到的用户id查询user_res表,然后根据查询到的数据给isHave字段赋值
        userPage.setRecords(setUserIsHaveRes(userPage.getRecords(), resId));
        return Response.success(userPage);
    }


    @ApiOperation(value = "我的资源下载接口文档")
    @ApiImplicitParam(name = "resId", value = "资源id")
    @GetMapping("/downloadResWord")
    public void downloadResWord(Integer resId, HttpServletResponse response) throws IOException, TemplateException, BizException {
        RdResDetailsApi rdResDetailsApi = rdResDetailsApiService.getOne(new LambdaQueryWrapper<RdResDetailsApi>().eq(RdResDetailsApi::getResDirId, resId));
        RdResourceDir rdResourceDir = rdResourceDirService.getById(resId);
        Assert.isNull(rdResourceDir,"无法获取该资源信息");
        List<Map<String, Object>> requestList = new ArrayList<>();
        List<Map<String, Object>> responseList = new ArrayList<>();
        Map<String, Object> dataMap = new HashMap<>(16);
        if (rdResDetailsApi != null) {
            List<RdParameterInformation> rdParameterInformations = rdParameterInformationService
                    .list(Wrappers.<RdParameterInformation>lambdaQuery().eq(RdParameterInformation::getOwnResId, rdResDetailsApi.getId()));
            dataMap.put("wordName",rdResourceDir.getResName());
            dataMap.put("interfaceAddress", rdResDetailsApi.getApiAddress());
            dataMap.put("interfaceDesc", rdResDetailsApi.getApiDesc());
            if (!rdParameterInformations.isEmpty()) {
                for (int j = 0; j < rdParameterInformations.size(); j++) {
                    RdParameterInformation rd = rdParameterInformations.get(j);
                    if (rd.getParameterType() == 0) {
                        Map<String, Object> requestMap = new HashMap<>(16);
                        requestMap.put("requestParamName", rd.getParameterName());
                        requestMap.put("requestParamType", rd.getType());
                        requestMap.put("requestParamDesc", rd.getExplains());
                        requestMap.put("required", rd.getNecessary() != null && rd.getNecessary() == 0 ? "是"
                                : rd.getNecessary() != null && rd.getNecessary() == 1 ? "否" : rd.getNecessary());
                        dataMap.put("requestResult", rdResDetailsApi.getRequestDemo());
                        requestList.add(requestMap);
                    } else if (rd.getParameterType() == 1) {
                        Map<String, Object> responseMap = new HashMap<>(16);
                        responseMap.put("responseParamName", rd.getParameterName());
                        responseMap.put("responseParamType", rd.getType());
                        responseMap.put("responseParamDesc", rd.getExplains());
                        responseMap.put("desc", rd.getExplains());
                        dataMap.put("responseResult", rdResDetailsApi.getReturnDemo());
                        responseList.add(responseMap);
                    }
                }
            }
        }
        dataMap.put("requestList", requestList);
        dataMap.put("responseList", responseList);
        @SuppressWarnings("deprecation")
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(this.getClass(), "/file");
        //文件名，获取模板
        response.setContentType("application/msword");
        response.setHeader("Content-Disposition", "attachment;fileName=" + new String((rdResourceDir.getResName()+".doc").getBytes("GBK"), "ISO-8859-1"));
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        Template template = configuration.getTemplate("浙江杭州数据资源局可信身份认证.ftl", "utf-8");
        template.process(dataMap, out);
        out.flush();
        out.close();
    }

    /**
     * 根据传入的用户列表查询用户资源表判断该用户是否拥有该资源权限，在返回的列表中isHave参数显示
     *
     * @param list
     * @param resId
     * @return
     */
    private List<UserInfoVo> setUserIsHaveRes(List<UserInfoVo> list, Integer resId) {
        if (list.isEmpty()) {
            return list;
        }
        List<RdResManagement> userResList = rdResManagementService.list(Wrappers.<RdResManagement>lambdaQuery().in(RdResManagement::getUserId,
                list.stream().map(user -> user.getId()).collect(Collectors.toList())).eq(RdResManagement::getResId, resId));
        userResList.forEach(userRes -> {
            list.forEach(user -> {
                if (userRes.getUserId().equals(user.getId())) {
                    user.setIsHave(1);
                }
            });
        });
        return list;
    }

}
